import {toast} from "../../utils/tool";

const app = getApp()
Page({
    data: {
        list: [],
        page: 1,
        hasMore: true,
    },
    format(time) {
        const date = new Date(time * 1000)
        const [year, month, day] = [date.getFullYear(), date.getMonth() + 1, date.getDate()]
        const [hour, minute, seconds] = [date.getHours(), date.getMinutes(), date.getSeconds()]
        return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day} ${hour < 10 ? '0' + hour : hour}:${minute < 10 ? '0' + minute : minute}:${seconds < 10 ? '0' + seconds : seconds}`
    },
    initData() {
        let {list: _list, hasMore: flag, page} = this.data
        if (!flag) return
        app.ajax({
            url: '/api/food/foodorderlistbyuser',
            data: {page},
            success: resp => {
                const {code, data: respData, msg} = resp
                if (code !== 1) return toast({time: msg})
                const {food_order, food_order_product} = respData
                const {current_page, total, data, per_page} = food_order
                const list = data.map((item, index) => {
                    const goodList = food_order_product[index] || []
                    const {createtime} = item
                    const goodCount = goodList.reduce((pre,cur)=>{
                        return pre + cur.count
                    },0)
                    const createTime = this.format(createtime)
                    return {...item, goodList, createTime,goodCount}
                })
                const hasMore = current_page * per_page < total
                if (hasMore) {
                    page += 1
                }
                this.setData({
                    hasMore,
                    page,
                    list: [..._list, ...list]
                })
            }
        })
    },

    onLoad: function () {
        this.initData()
    }
});